package com.zdsoft.site.mina.state;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.service.IoHandler;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineEncoder;
import org.apache.mina.statemachine.StateMachine;
import org.apache.mina.statemachine.StateMachineFactory;
import org.apache.mina.statemachine.StateMachineProxyBuilder;
import org.apache.mina.statemachine.annotation.IoHandlerTransition;
import org.apache.mina.statemachine.context.IoSessionStateContextLookup;
import org.apache.mina.statemachine.context.StateContext;
import org.apache.mina.statemachine.context.StateContextFactory;
import org.apache.mina.transport.socket.SocketAcceptor;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class Main {
	
	private static IoHandler createIoHandler() {
		StateMachine sm = StateMachineFactory.getInstance(IoHandlerTransition.class).create(PlayGameHandler.EMPTY, new PlayGameHandler());
		// return new StateMachineProxyBuilder().create(IoHandler.class, sm);
		return new StateMachineProxyBuilder().setStateContextLookup(new IoSessionStateContextLookup(new StateContextFactory() {
			public StateContext create() {
				return new PlayGameHandler.GameContext();
			}
		})).create(IoHandler.class, sm);
	}

	public static void main(String[] args) throws IOException {
		SocketAcceptor sa = new NioSocketAcceptor();
		sa.setReuseAddress(true);
		ProtocolCodecFilter pcf = new ProtocolCodecFilter(new TextLineEncoder(), new CommandDecoder());
		sa.getFilterChain().addLast("mycodec", pcf);
		sa.setHandler(createIoHandler());
		sa.bind(new InetSocketAddress("localhost", 6002));
	}
}
